/**
 * Copyright (c) 2012, http://www.yissugames.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yissugames.blocklife;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.openal.AL;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;

import com.yissugames.blocklife.gamelogic.CraftingRecipes;

import static org.lwjgl.opengl.GL11.*;

/**
 * This is the main class from BlockLife
 * it create and init OpenGL and the window
 * Don't modify it when you don't know what you do
 * 
 * @author Jonas
 * @version 1.0
 * @see http://yissugames.com/yissugames/BlockLife/devwiki/index.php/BlockLife_(Klasse)
 */
public class BlockLife {

	public static final String font = "Arial";
	
	public static int DisplayWidth = 800;
	public static int DisplayHeight = 600;
	
	public static float BackgroundR = 1;
	public static float BackgroundG = 1;
	public static float BackgroundB = 1;
	
	public static String ApplicationFolder;
	public static String DS;
	
	public static boolean ExistsWorlds;
	public static final Logger log = Logger.getLogger(BlockLife.class.getName());
	
	/**
	 * Create and startup the game logic
	 */
	public BlockLife()
	{
		try {
		Display.setDisplayMode(new DisplayMode(DisplayWidth, DisplayHeight));
		Display.setTitle("BlockLife");
		Display.create();
		} catch (LWJGLException e) {
			e.printStackTrace();
			Display.destroy();
			System.exit(1);
		}
		
		initGL();
		
		Language.loadLanguage();
		ScreenSystem.setup();
		CraftingRecipes.init();
		ScreenSystem.set(new LoadScreen());
		
		String os = System.getProperty("os.name");
		if(os.startsWith("Windows")) // Windows is the operating system
		{
			DS = "\\";
			ApplicationFolder = System.getProperty("user.home") + DS + "AppData" + DS + "Roaming" + DS + "BlockLife" + DS;
		} else if(os.equals("Linux")) // Linux is the operating system
		{
			DS = "/";
			ApplicationFolder = System.getProperty("user.home") + DS + ".BlockLife" + DS;
		} else if(os.equals("Mac OS X")) // Mac OS X is the operating system
		{
			DS = "/";
			ApplicationFolder = System.getProperty("user.home") + DS + "Library" + DS + "Application Support" + DS + "BlockLife" + DS;
		} else { // Unsupported operating system
			Display.destroy();
			Sys.alert("Unsupported operating system", "Your operating system \"" + os + "\" isn't supported yet!");
			System.exit(1);
		}
		System.out.println("Saving files to: " + ApplicationFolder);
		if(!new File(ApplicationFolder).exists()) // Check if application folder exist
		{
			new File(ApplicationFolder).mkdir(); // Create application folder
			System.out.println("Application folder was created");
		}
		if(new File(ApplicationFolder + "world" + DS).exists())
			ExistsWorlds = true;
		
		Handler handler;
		try {
			handler = new FileHandler(new File(ApplicationFolder + "log").getAbsolutePath());
			log.addHandler(handler);
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		// The Game Loop
		while(!Display.isCloseRequested())
		{
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			glClearColor(BackgroundR, BackgroundG, BackgroundB, 1);
			glLoadIdentity();
			
//			try {
				ScreenSystem.render();
//			} catch (Exception e) {
//				Sys.alert("Uncaughted exception", "BlockLife run into a problem... Sorry!");
//				String stackTrace = stackTraceToString(e.getStackTrace());
//				log.log(Level.SEVERE, e.getMessage() + System.getProperty("line.separator") + stackTrace);
//				System.exit(1);
//			}
			
			Display.sync(60);
			Display.update();
		}
		
		AL.destroy();
		ScreenSystem.destory();
		Display.destroy();
	}
	
	private static String stackTraceToString(StackTraceElement[] stackTrace)
	{
		StringBuilder result = new StringBuilder();
		String NEW_LINE = System.getProperty("line.separator");
		
		for(StackTraceElement element: stackTrace) {
			result.append(element);
			result.append(NEW_LINE);
		}
		
		return result.toString();
	}
	
	private static void initGL()
	{	
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(0, DisplayWidth, DisplayHeight, 0, 0, -1);
		glMatrixMode(GL_MODELVIEW);
		
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}
	
	/**
	 * Automatically called by java
	 * @param args Command line parameters
	 */
	public static void main(String[] args)
	{
		new BlockLife();										// Create a new instance 
	}
	
}
